package com.polaris.live.ui.live.widget.adapter

import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import androidx.core.view.doOnLayout
import androidx.lifecycle.LifecycleCoroutineScope
import com.blankj.utilcode.util.SpanUtils
import com.polaris.live.adapter.live.LiveMessageAdapter
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.util.loadIfPresent
import com.polaris.live.databinding.LiveMessageRecommendCardItemBinding
import com.polaris.live.im.sfs.bean.live.SendLiveMessage
import com.polaris.live.im.sfs.bean.live.ext.MessageUserExtBean
import com.polaris.live.ui.live.widget.LiveFloatView
import com.polaris.live.ui.message.widget.single_message.AbstractLiveMessageItemHolder
import com.polaris.live.utils.CommonUtils
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.viewscope.autoDisposeScope
import com.polaris.live.widget.avatar.FrameImageUtils
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 用户使用推荐卡片消息
 *
 * @author Created by 半仙 on 2024/8/12/012 17:21
 */
class LiveMessageRecommendCardItem(
    adapter: LiveMessageAdapter,
    binding: LiveMessageRecommendCardItemBinding,
    private val lifecycleScope: LifecycleCoroutineScope?
) : AbstractLiveMessageItemHolder<LiveMessageRecommendCardItemBinding>(adapter, binding) {

    override fun bind(item: SendLiveMessage) {
        mBinding.apply {
            val ext = item.ext as? MessageUserExtBean?
            avatarImg.setImageUrl(ext?.user?.avatar, ext?.user?.userId)
            avFv.setFrameImage(FrameImageUtils.urlToFrameImageBean(ext?.user?.avatarFrame))

            CommonUtils.setNumberMedal(lifecycleScope, ext?.user?.numberMedal, mBinding.pagImageMe, mBinding.ivImageMe)

            loadIfPresent({ item.span1 }, {
                mBinding.root.autoDisposeScope.launch {
                    try {
                        val span = CommonUtils.setSpanData(liveHead, item, mAdapter.context)
                        withContext(CoroutineScopeManager.mainDispatcher) {
                            emit(span.create())
                        }
                    } catch (_: Exception) {
                    }
                }
            }, {
                liveHead.text = it
                item.span1 = it
            })
            tvContent.text = " "

            loadIfPresent({ item.span2 }, {
                tvContent.doOnLayout {// doOnLayout 使用他是因为只会在视图完成布局后触发一次之后不会继续监听布局变化，生命周期较短，不需要手动移除监听器，在视图的布局完成后立即执行
                    val span = SpanUtils.with(tvContent)
                    val splitMessage = item.content.split(LiveFloatView.SPLIT)
                    mBinding.root.autoDisposeScope.launch {
                        try {
                            splitMessage.forEach {
                                if (it.contains(LiveFloatView.IMAGEAND)) {
                                    val modifiedStr = it.replace(LiveFloatView.IMAGEAND, "")
                                    val icon = ImageUtils.loadNetImageBitmapNoTransform(root.context, modifiedStr)
                                    if (icon != null && !icon.isRecycled) {
                                        val resizedBitmap = resizeBitmapHeight(icon, tvContent.height)
                                        val drawable = BitmapDrawable(mBinding.root.resources, resizedBitmap)
                                        drawable.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
                                        span.appendImage(icon, SpanUtils.ALIGN_CENTER)
                                    }
                                } else {
                                    span.append(it)
                                }
                            }
                            withContext(CoroutineScopeManager.mainDispatcher) {
                                emit(span.create())
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
            }, {
                tvContent.text = it
                item.span2 = it
            })

        }
    }

    private fun resizeBitmapHeight(bitmap: Bitmap, targetHeight: Int): Bitmap {
        val aspectRatio = bitmap.width.toFloat() / bitmap.height
        val targetWidth = (targetHeight * aspectRatio).toInt()
        return Bitmap.createScaledBitmap(bitmap, targetWidth, targetHeight, false)
    }

}